﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMK.PaketTracker.Server.Definitions;
using System.Data.SqlClient;
using System.Data;

namespace MMK.PaketTracker.Server.Database
{
    public class PaketSqlDataLayer : BaseSqlDataLayer
    {
        public PaketSqlDataLayer(string DbConnectionString) { this.Initialize(DbConnectionString); }
        
        public void CreateNewPaket(Paket paket)
        {
            string sql = "INSERT INTO [Pakete] VALUES (@Ident, @Zeitstempel, @Gewicht, @Preis)";

            this.ExecuteNonQuery(sql,
                new SqlParameter("@Ident", paket.Ident),
                new SqlParameter("@Zeitstempel", DateTime.Now),
                new SqlParameter("@Gewicht", paket.Gewicht),
                new SqlParameter("@Preis", paket.Preis));
        }

        public Paket LoadPaket(string paketIdent)
        {
            string sql = "SELECT * FROM [Pakete] WHERE Ident=@Ident";

            using (IDataReader reader = this.GetDataReader(sql, new SqlParameter("@Ident", paketIdent)))
            {
                return (reader.Read() ? LoadPaketFromDataReader(reader) : null);
            }
        }

        private Paket LoadPaketFromDataReader(IDataReader reader)
        {
            Paket paket = new Paket();
            paket.Ident = this.GetString(reader, "Ident");
            paket.Zeitstempel = this.GetDateTime(reader, "Zeitstempel");
            paket.Gewicht = this.GetDouble(reader, "Gewicht");
            paket.Preis = this.GetDouble(reader, "Preis");

            return paket;
        }
    }
}
